// pages/user/register.js
import { registerApi } from '../../api/user.js'

Page({
  data: {
    username: '',
    mobile: '',
    email: '',
    password: '',
    confirmPassword: '',
    errorMsg: ''
  },

  onLoad() {
    // 初始化操作
  },

  // 输入框绑定事件
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [field]: e.detail.value
    });
  },

  // 表单提交
  async handleSubmit() {
    const { username, mobile, email, password, confirmPassword } = this.data;
    const error = this.validateForm();
    if (error) {
      this.setData({ errorMsg: error });
      return;
    }

    try {
      const res = await registerApi({ username, mobile, email, password });
      if (res.code === 200) {
        uni.showToast({ title: '注册成功', icon: 'success' });
        uni.navigateBack({ delta: 1 }); // 返回上一页或跳转到登录页
      } else {
        this.setData({ errorMsg: res.msg || '注册失败，请重试' });
      }
    } catch (err) {
      this.setData({ errorMsg: '网络请求失败' });
    }
  },

  // 表单校验
  validateForm() {
    const { username, mobile, email, password, confirmPassword } = this.data;
    if (!username.trim()) return '请输入用户名';
    if (!/^1[3-9]\d{9}$/.test(mobile)) return '手机号格式不正确';
    if (email && !/^[\w.-]+@[\w.-]+\.\w+$/.test(email)) return '邮箱格式不正确';
    if (password.length < 6) return '密码至少6位';
    if (password !== confirmPassword) return '两次输入的密码不一致';
    return null;
  }
});